import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geolocator/geolocator.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_view/photo_view.dart';


import '../../AppConfig/Config.dart';
import 'package:image/image.dart' as img;

import 'package:platform/platform.dart';

import '../../AppConfig/ShowDialog.dart';
import '../../TabBar/TabbarView.dart';
import '../../http/NoLoadingPostApi.dart';
import '../../http/api.dart';
class UploadPhotoPage extends StatefulWidget {
  const UploadPhotoPage({super.key, required this.uploadType, required this.dataMap});
  //1.装货 2.卸货 3.回单
  final int uploadType;
  final Map dataMap;
  @override
  State<UploadPhotoPage> createState() => _UploadPhotoPageState();
}

class _UploadPhotoPageState extends State<UploadPhotoPage> {
  List imagePaths = [];
  List base64List=[];
  String? checkImage;
  int chkecType=-1;
  List getFileList=[];
  String company="";
  String phone="";
  String order ="";
  final ImagePicker picker = new ImagePicker();
  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();
  bool _suc = false;
  double Latitude=0;
  double Longitude=0;
  bool isRange=true;
  bool isShow=false;
  Random random = Random();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.uploadType!=3)
    getLocation();

  }
  void getLocation() async {
    var status = await Permission.location.status;
    if (status!=PermissionStatus.denied&&status!=PermissionStatus.permanentlyDenied) {
      setState(() {
        isShow=true;
      });
    }else {
      Position position = await Geolocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.high);
      print(position);
      print("1111");
      setState(() {
        Latitude = position.latitude;
        Longitude = position.longitude;
        checkGeofence(Latitude, Longitude);
      });
    }
  }

  Future<void> checkGeofence(double Latitude,double Longitude ) async {
    // 假设这是你的地理围栏的中心和半径
    double fenceLatitude = widget.dataMap['goodsInfo']['loadPlaceInfo'][0]['latitude'];
    double fenceLongitude = widget.dataMap['goodsInfo']['loadPlaceInfo'][0]['longitude'];
    double fenceRadius = 10.0; // 单位是公里

    double distance = await Geolocator.distanceBetween(
      Latitude,
      Longitude,
      fenceLatitude,
      fenceLongitude,
    );

    if (distance <= fenceRadius * 1000) {
      print('你在地理围栏范围内');
      setState(() {
        isRange=true;
      });
    } else {
      print('你不在地理围栏范围内');
      setState(() {
        isRange=false;
      });
    }
  }
  BaiduLocationIOSOption initIOSOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
        coordType: BMFLocationCoordType.bd09ll,
        BMKLocationCoordinateType: 'BMKLocationCoordinateTypeBMK09LL',
        desiredAccuracy: BMFDesiredAccuracy.best);
    return options;
  }
  void _locationAction() async {
    /// 设置android端和ios端定位参数
    /// android 端设置定位参数
    /// ios 端设置定位参数
    Map iosMap = initIOSOptions().getMap();
    Map androidMap = initAndroidOptions().getMap();

    _suc = await _myLocPlugin.prepareLoc(androidMap, iosMap);
    print('设置定位参数：$iosMap');
  }
  /// 启动定位
  Future<void> _startLocation() async {
    if (LocalPlatform().isIOS) {
      _suc = await _myLocPlugin
          .singleLocation({'isReGeocode': true, 'isNetworkState': true});
      print('开始单次定位：$_suc');
    } else if (LocalPlatform().isAndroid) {
      _suc = await _myLocPlugin.startLocation();
    }
  }
  /// 设置地图参数
  BaiduLocationAndroidOption initAndroidOptions() {
    BaiduLocationAndroidOption options = BaiduLocationAndroidOption(
        coorType: 'bd09ll',
        locationMode: BMFLocationMode.hightAccuracy,
        isNeedAddress: true,
        isNeedAltitude: true,
        isNeedLocationPoiList: true,
        isNeedNewVersionRgc: true,
        isNeedLocationDescribe: true,
        openGps: true,
        locationPurpose: BMFLocationPurpose.sport,
        coordType: BMFLocationCoordType.bd09ll);
    return options;
  }
  //获取图片路径
  Future<void> uploadSingleFile(String fileData) async {
    NoLoadingApiManager.postData(
      context,
      'api/system/dev/file/uploadSingleFile',
      {
        "type":widget.uploadType==1?"WaybillLoadDocument":widget.uploadType==2?"WaybillUnloadDocument":"WaybillReturnDocument",
        "typeKey":widget.dataMap['id'],
        "fileData":fileData,
        "fileFormat":"jpg",
        "fileName":(100000 + random.nextInt(999999 - 100000)).toString(),
      },
          (responseData)  {
        getFileList.add(responseData['data']);
        if(widget.uploadType==1)
          clockAlreadyLoad();
        if(widget.uploadType==2)
          clockAlreadyUnload();
        if(widget.uploadType==3)
          clockAlreadyReturn();
      },
    );
  }
  //上传回单
  Future<void> clockAlreadyReturn() async {
    print(getFileList);
   ApiManager.postData(
      context,
      'api/waybill/driver/waybill/confirmReturn',
      {
        "waybillId":widget.dataMap['id'],
        "returnPathList":getFileList,
      "expressCompany": company,
      "expressNum": order,
      "expressContact": phone
      },
          (responseData)  {
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
            );

      },
    );
  }
//确认装货
  Future<void> clockAlreadyLoad() async {
    print(getFileList);
    ApiManager.postData(
      context,
      'api/waybill/driver/waybill/confirmLoad',
      {"waybillId":widget.dataMap['id'],
        "loadPathList":getFileList,
        "inLoadPlace": isRange?1:0,
        "longitude": Longitude,
        "latitude": Latitude
      },
          (responseData)  {
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
            );


      },
    );
  }
  //确认卸货
  Future<void> clockAlreadyUnload() async {
    print(getFileList);
    ApiManager.postData(
      context,
      'api/waybill/driver/waybill/confirmUnload',
      {"waybillId":widget.dataMap['id'],
        "unloadPathList":getFileList,
        "inUnloadPlace": isRange?1:0,
        "longitude": Longitude,
        "latitude": Latitude
      },
          (responseData)  {
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
            );


      },
    );
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("上传照片",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ),
      body: Column(
        children: [
          Expanded(
              child: ListView(
                children: [
                  if(isShow)
                    GestureDetector(
                      child: Container(
                        width: screenSize.width,
                        padding: EdgeInsets.only(top: 8.h,bottom: 8.h,left: 10.w,right: 10.w),
                        color:  Color.fromRGBO(251, 236, 228, 1),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Icon(Icons.error,color: Colors.red,size: 20,),
                            Container(
                              width: screenSize.width-50.w,
                              child:   Text("请开启定位功能，否则将无法提交图片信息",
                                style: TextStyle(color: Colors.red,fontSize: 14.sp),),
                            ),

                          ],
                        ),
                      ),
                      onTap: (){
                        openAppSettings();
                      },
                    ),
                  if(!isRange&&widget.uploadType!=3&&!isShow)
                    Container(
                      width: screenSize.width,
                      padding: EdgeInsets.only(top: 8.h,bottom: 8.h,left: 10.w,right: 10.w),
                      color:  Color.fromRGBO(251, 236, 228, 1),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Icon(Icons.error,color: Colors.red,size: 20,),
                          Container(
                            width: screenSize.width-50.w,
                            child:   Text("您当前不在有效的装货范围内，请到距离装货地10KM范围内再进行操作",
                              style: TextStyle(color: Colors.red,fontSize: 14.sp),),
                          ),

                        ],
                      ),
                    ),

                  Container(
                    margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                    padding: EdgeInsets.only(left: 12.w,right: 12.w,top: 10.h,bottom: 10.h),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 20.sp),),
                            Text(widget.uploadType==1?"装货凭证":widget.uploadType==2?"卸货凭证":"回单凭证",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                          ],
                        ),
                        Container(
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Wrap(
                              spacing: 8.0,
                              runSpacing: 8.0,
                              children: [
                                ...imagePaths.map((path) => buildImageWidget(path)).toList(),
                                buildAddImageWidget(1),
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  if(widget.uploadType==3)
                  Container(
                    margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                    padding: EdgeInsets.only(left: 12.w,right: 12.w,top: 12.h,bottom: 12.h),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Text("物流公司",style: TextStyle(color:Colors.black,fontSize: 14.sp ),),
                                Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                              ],
                            ),
                            Container(
                              width: 200.w,
                              height:20.h,
                              color: MyColors.backgreyColor,
                              child:  TextField(
                                decoration: InputDecoration(
                                  hintText: '请填写',
                                  hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.hintColor),
                                  filled: true,
                                  fillColor: Colors.white,
                                  border: InputBorder.none,
                                  alignLabelWithHint: true,
                                  contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                                ),
                                // keyboardType: TextInputType.number,
                                textAlign: TextAlign.right,
                                style: TextStyle(color: Colors.black,fontSize: 14.sp),
                                onChanged: (value) {
                                  setState(() {
                                   company=value;
                                  });
                                },
                              ),
                            ),
                          ],
                        ),
                        Divider(height: 16.h,color: MyColors.backgreyColor,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Text("物流单号",style: TextStyle(color:Colors.black,fontSize: 14.sp ),),
                                Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                              ],
                            ),
                            Container(
                              width: 200.w,
                              height:20.h,
                              color: MyColors.backgreyColor,
                              child:  TextField(
                                decoration: InputDecoration(
                                  hintText: '请填写',
                                  hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.hintColor),
                                  filled: true,
                                  fillColor: Colors.white,
                                  border: InputBorder.none,
                                  alignLabelWithHint: true,
                                  contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                                ),
                                keyboardType: TextInputType.number,
                                textAlign: TextAlign.right,
                                style: TextStyle(color: Colors.black,fontSize: 14.sp),
                                onChanged: (value) {
                                  setState(() {
                                    order=value;
                                  });
                                },
                              ),
                            ),
                          ],
                        ),
                        Divider(height: 16.h,color: MyColors.backgreyColor,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [

                            Text("联系电话",style: TextStyle(color:Colors.black,fontSize: 14.sp ),),

                            Container(
                              width: 200.w,
                              height:20.h,
                              color: MyColors.backgreyColor,
                              child:  TextField(
                                decoration: InputDecoration(
                                  hintText: '选填',
                                  hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.hintColor),
                                  filled: true,
                                  fillColor: Colors.white,
                                  border: InputBorder.none,
                                  alignLabelWithHint: true,
                                  contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                                ),
                                keyboardType: TextInputType.number,
                                textAlign: TextAlign.right,
                                style: TextStyle(color: Colors.black,fontSize: 14.sp),
                                onChanged: (value) {
                                  setState(() {
                                    phone = value;
                                  });
                                },
                              ),
                            ),
                          ],
                        ),

                      ],
                    ),
                  ),
                ],
              ),
          ),
          Container(
            height: 85.h,
            color: Colors.white,
            padding: EdgeInsets.only(left: 15.w,right: 15.w,top:10.h,bottom: 44.h ),
            child:
                BrnSmallMainButton(
                  title: '提交',
                  bgColor:MyColors.themeColor,
                  radius: 30,
                  width: screenSize.width-30.w,
                  fontSize: 16.sp,
                  onTap: () {

                    if(isShow){
                      BrnToast.show("请开启定位功能，否则将无法提交图片信息", context);
                    }else {
                      BrnDialogManager.showConfirmDialog(context,
                          title: "提示",
                          message: "确认提交图片吗？",
                          cancel: "",
                          cancelWidget: GestureDetector(
                            child: Center(
                              child: Text("我再想想", style: TextStyle(
                                  color: Colors.black, fontSize: 14.sp),),
                            ),
                            onTap: () {
                              Navigator.pop(context);
                            },
                          ),
                          conformWidget: GestureDetector(
                            child: Center(
                              child: Text("确认", style: TextStyle(
                                  color: MyColors.themeColor,
                                  fontSize: 14.sp),),
                            ),
                            onTap: () {
                              Navigator.pop(context);
                              for (int i = 0; i < base64List.length; i++) {
                                String index = base64List[i];
                                uploadSingleFile(index);
                              }
                            },
                          ),
                          confirm: "",
                          onConfirm: () {},
                          onCancel: () {});
                    }
                  },
                ),
          ),
        ],
      ),
    );
  }
  Widget buildImageWidget(String imagePath) {
    return Container(
      width: 85.w,
      height: 85.h,
      child: Stack(
        children: [
          GestureDetector(
            onTap: () {
              // 处理点击查看图片的逻辑
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => ImageViewer(imagePath),
                ),
              );
            },
            child: Container(
              width: 75.w,
              height: 75.h,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: FileImage(File(imagePath)),
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.circular(8.0),
              ),
            ),
          ),

          Positioned(
            top: 0,
            right: 0,
            child: GestureDetector(
              child: Icon(Icons.highlight_off,size: 30,color: MyColors.authTipColor,),
              onTap: () {
                setState(() {
                  imagePaths.remove(imagePath);
                });
              },
            ),
          ),
        ],
        alignment: Alignment.center,
      ),
    );


      


  }

  Widget buildAddImageWidget(int checkType) {
    return GestureDetector(
        onTap: () async {
          setState(() {
            chkecType=checkType;
          });
          showModalBottomSheet(context: context, builder: (BuildContext context) {
            return Container(
              color: Colors.white,
              child:
              Stack(

                children: [

                  Column(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment:MainAxisAlignment.center,

                    children:[

                      SizedBox(height: 8.h,),
                      Row(
                        mainAxisAlignment:MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(width: 30.w,),
                          Text("上传照片",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                          IconButton(onPressed: (){
                            Navigator.of(context).pop();
                          }, icon:Icon(Icons.close,color: MyColors.textColor,)),
                        ],
                      ),


                      SizedBox(height: 8.h,),
                      Row(
                        children: [
                          SizedBox(width: 38.w,),
                          GestureDetector(
                            child:   Column(
                              children: [
                                Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                Text("相册",style: TextStyle(color: Colors.black),),

                              ],

                            ),
                            onTap: ()async{
                              var status = await Permission.photos.request();
                              if(status==PermissionStatus.denied){
                                showPhotosFirstDialog(context);
                              }else if(status==PermissionStatus.permanentlyDenied){
                                showPhotosDialog(context);
                              }else {
                                Navigator.of(context).pop();
                                final pickedFile = await picker.pickImage(
                                    source: ImageSource.gallery);

                                if (pickedFile != null) {
                                  setState(() {
                                    checkImage = pickedFile.path;
                                    printImageMemorySize(File(checkImage!));
                                    print(checkImage);
                                    compressImage(File(checkImage!));
                                  });
                                }
                              }
                            },
                          ),

                          SizedBox(width: 38.w,),
                          GestureDetector(
                            child: Column(
                              children: [
                                Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                Text("拍照",style: TextStyle(color: Colors.black),),

                              ],

                            ),
                            onTap: ()async{
                              var status = await Permission.camera.request();
                              if(status==PermissionStatus.denied){
                                showCameraFirstDialog(context);
                              }else if(status==PermissionStatus.permanentlyDenied){
                                showCameraDialog(context);
                              }else {
                                Navigator.of(context).pop();
                                final pickedFile = await picker.pickImage(
                                    source: ImageSource.camera);

                                if (pickedFile != null) {
                                  setState(() {
                                    checkImage = pickedFile.path;
                                    printImageMemorySize(File(checkImage!));
                                    print(checkImage);
                                    compressImage(File(checkImage!));
                                  });
                                }
                              }
                            },
                          ),

                        ],
                      ),
                      SizedBox(height: 40.h,),
                    ],

                  ),

                ],

              ),
            );


          });


        },
        child: Image.asset("lib/Images/OrderList/图片管理上传照片.png",width: 85.w,height: 85.h,)
    );
  }

  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    print('Original Image Memory Size: ${imageBytes.length} bytes');
  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    print('Compressed Image Size: ${compressedBytes.length} bytes');

    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);
    base64List.add(base64String);
    setState(() {
      imagePaths.add(checkImage.toString());

    });
  }


}
class ImageViewer extends StatelessWidget {
  final String imagePath;

  ImageViewer(this.imagePath);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          // 当点击大图时，返回上一个页面
          Navigator.pop(context);
        },
        child: PhotoView(
          imageProvider: FileImage(File(imagePath)),
          minScale: PhotoViewComputedScale.contained * 0.8,
          maxScale: PhotoViewComputedScale.covered * 2,
        ),
      ),
    );
  }
}
